package com.jueyunqi.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.dubbo.common.utils.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.jueyunqi.service.EmployeeService;
import com.jueyunqi.simple.entity.Employee;

@Controller
@RequestMapping("/")
public class WebController {
	@Resource
	private EmployeeService employeeService;
	
	/**
	 * 
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login.htm", method = RequestMethod.GET)
	public String loginView(Model model){
		return "login";
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @param session
	 * @param model
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/login.htm", method = RequestMethod.POST)
	@ResponseBody
	public String loginEvent(HttpServletRequest request, HttpServletResponse response,
			HttpSession session, Model model, @RequestBody Employee employee)
		throws Exception
	{
		if(null == employee || null == employee.getName()){
			throw new Exception("用户信息为空！");
		}
		
		JSONObject ret = new JSONObject();
		
		Long id =null;
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("name", employee.getName());
		List<Employee> employees = employeeService.queryEmployees(params);
		if(CollectionUtils.isNotEmpty(employees)){
			for (Employee item : employees) {
				if(Objects.equals(item.getName(), employee.getName()) 
						&& Objects.equals(item.getPasswd(), employee.getPasswd())){
					id = item.getId();
					break;
				}
			}
		}
		
		if(null == id){
			ret.put("msg", 0);
		}else {
			session.setAttribute("userId", id);
			ret.put("msg", 1);
		}
		
		String userAgent = request.getHeader("User-Agent");
		if (userAgent.contains("MSIE 9"))
		{
			response.setContentType("text/plain");
		}
		
		return JSONObject.toJSONString(ret);
	}
	
	/**
	 * 
	 * @param session
	 * @param model
	 * @param employee
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/register.json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Integer> register(HttpSession session, Model model, @RequestBody Employee employee)
		throws Exception
	{
		if(null == employee || null == employee.getName() || null == employee.getPasswd()){
			throw new Exception("用户信息为空！");
		}
		try {
			Long id = employeeService.addEmployee(employee);
			session.setAttribute("userId", id);
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
		
		Map<String, Integer> ret = new HashMap<String, Integer>();
		ret.put("msg", 1);
		return ret;
	}
	
	/**
	 * 
	 * @param session
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public String indexView(HttpSession session, Model model)
			throws Exception
	{
		Long id = (Long) session.getAttribute("userId");
		if(null == id){
			throw new Exception("用户id不存在！");
		}
		
		Employee employee = employeeService.findById(id);
		if(null == employee){
			throw new Exception("用户信息为空！");
		}
		model.addAttribute("name", employee.getName());
		return "index";
	}
	
	/**
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/link/{id}.htm", method = RequestMethod.GET)
	public String linkView(Model model,@PathVariable(value="id") Integer id){
		model.addAttribute("id", id);
		return "link";
	}
	
	/**
	 * 暂存数据到session
	 * @param session
	 * @param jsonStr
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/save_in_session.json", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveInSession(HttpSession session, String jsonStr)
		throws Exception
	{
		Map<String, Object> ret = new HashMap<String, Object>();
		if(null == jsonStr){
			ret.put("result", 0);
		}else {
			String key=UUID.randomUUID().toString();
	    	session.setAttribute(key, jsonStr);
	    	ret.put("result", 1);
	    	ret.put("key", key);
		}
		return ret;
	}
	
	/**
	 * 上传文件
	 * @param request
	 * @param response
	 * @param uploadFile
	 * @param jsonKey
	 */
	@RequestMapping(value="/uploading.htm")
	public void uploadExcel(HttpServletRequest request, HttpServletResponse response,
			@RequestParam("uploadFile") MultipartFile uploadFile,
			@RequestParam("jsonKey") String jsonKey){
		JSONObject jsonObject = null;
		if(null != jsonKey){
			jsonKey=jsonKey.trim();
			
			HttpSession session = request.getSession();
			Object obj = session.getAttribute(jsonKey);
			if(null != obj){
				request.getSession().removeAttribute(jsonKey);
				jsonObject = JSONObject.parseObject(obj.toString());
			}
		}
		if(null != jsonObject){
			System.out.println(jsonObject.toJSONString());
		}
		
		//写入上传文件到磁盘  
		//可以配置分布式文件服务器 fastDFS
		String path=request.getServletContext().getRealPath("upload");
		File dir = new File(path);
		if (!dir.isDirectory()) {
			dir.mkdir();
		}
		File file = new File(path+File.pathSeparator+uploadFile.getOriginalFilename());
		FileOutputStream out = null;
		try {
			InputStream in = uploadFile.getInputStream();
			out = new FileOutputStream(file);
			byte[] arr = new byte[512];
			int count = 0;
			while(0 < (count = in.read(arr))){
				out.write(arr, 0, count);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
